const fs = require("fs");
const path = require("path");
const cityDatas = require('./datas/citydata')

let zhixias = ["北京市", "上海市", "天津市", "重庆市"];
let provinces = cityDatas[86];
let districts = [];

/**
 * 生成地区列表(含省市)。
 */
let BuildAreas = () => {
  provinces.forEach(function(item) {
    let province = cityDatas[item.code];
    let cities = Object.getOwnPropertyNames(province);

    if (!zhixias.find(i => i == item.address)) {
      districts.push(item.address);
      // districts.push({ code: item.code, name: item.address });
    }

    cities.forEach(function(c) {
      let city = cityDatas[c];

      if (city) {
        districts.push(item.address + "/" + province[c]);
        // districts.push({ code: c, name: item.address + "/" + province[c] });

        let dists = Object.getOwnPropertyNames(city);
        dists.forEach(function(d) {
          districts.push(item.address + "/" + province[c] + "/" + city[d]);
          //   districts.push({
          //     code: d,
          //     name: item.address + "/" + province[c] + "/" + city[d]
          //   });
        });
      }
    });
  });

  fs.writeFile(
    path.resolve(__dirname, "../districts.json"),
    JSON.stringify(districts),
    {
      encoding: "utf8"
    },
    function(errr) {
      console.log(errr);
    }
  );
};

let BuildAreaDatas = () => {
  let datas = {
    provinces: []
  };

  provinces.forEach(function(item) {
    let pitem = {
      value: item.code,
      label: item.address
    };

    datas.provinces.push(pitem);

    // 省下面的市
    let provinceCities = [];
    pitem.children = provinceCities;

    let province = cityDatas[item.code];
    let cities = Object.getOwnPropertyNames(province);

    cities.forEach(function(c) {
      let city = cityDatas[c];

      if (city) {
        let citem = {
          value: c,
          label: province[c]
        };

        // 添加省下面的市
        provinceCities.push(citem);

        let dists = Object.getOwnPropertyNames(city);

        let cityDistricts = [];
        citem.children = cityDistricts;

        dists.forEach(function(d) {
          cityDistricts.push({
            value: d,
            label: city[d]
          });
        });
      }
    });
  });

  fs.writeFile(
    path.resolve(__dirname, "../city-data.json"),
    JSON.stringify(datas.provinces),
    {
      encoding: "utf8"
    },
    function(errr) {
      console.log(errr);
    }
  );
};

BuildAreaDatas();
